/**
 * 
 * @param {*element for table} table
 * @param {*element for form} form
 * @param {*element for delete} selectorDelete 
 * @param {*element for add new} selectorAdd 
 * @param {*element for eidt} selectorEdit 
 */

function tableOperator(table, form, selectorDelete, selectorAdd, selectorEdit) {
    var table = $(table),
        inputs = $(form + " input[data-field]");
    var rowIDs = [];
    inputs.each(function () {
        rowIDs.push($(this).attr("data-field"));
    });

    // 删除行
    $(selectorDelete).click(function () {
        var a = table.bootstrapTable("getSelections");
        b = $.map(a, function (row) {
            return row.id;
        });
        table.bootstrapTable("remove", {
            field: "id",
            values: b
        });
    });

    // 修改行
    $(selectorEdit).click(function (e, add) {
        var a = table.bootstrapTable("getSelections");
        var b = table.bootstrapTable("getData"),
            idx = null;
        if (a.length && !add) {
            for (var i = 0, j = b.length; i < j; i++) {
                if (b[i].id === a[0].id) {
                    idx = i;
                    break;
                }
            }
        } else if (add) {
            idx = b.length;
        }

        var row = {};
        if (a.length && !add) {
            inputs.each(function (index, element) {
                this.value = a[0][rowIDs[index]];
            })
        } else if (add || !a.length) {
            inputs.each(function (index, element) {
                this.value = "";
            })
        }

        $(form + " button").eq(0).one("click", function (e) {
            e.preventDefault(); //测试用，阻断表单提交

            inputs.each(function (index, element) {
                row[rowIDs[index]] = this.value.trim() || "-";
            })
            row.createtime = new Date().toLocaleDateString();
            if (a.length && !add) {
                table.bootstrapTable("updateRow", {
                    index: idx,
                    row: row
                });
            } else if (add) {
                table.bootstrapTable("insertRow", {
                    index: idx,
                    row: row
                });
            }
        });

        // 测试用，阻断表单提交
        $(form + " button").click(function (e) {
            e.preventDefault();
        })
    });

    // 新增行
    $(selectorAdd).click(function () {
        $("#edit").trigger("click", ["add"]);
    });
};

function showTable(table, columns, data) {
    $(table).bootstrapTable({
        height: 400,
        url: "",
        queryParams: "queryParams",
        clickToSelect: true,
        pagination: true,
        toolbar: "#toolbar",
        columns: columns,
        data: data
    });

    $("#toolbar select").change(function () {
        console.log($(this).val()); // test

        $(table).bootstrapTable("refresh", {
            silent: true,
            query:{}
        });
    });
};